import uuid
from flaskapp.model.db import db, User
from sqlalchemy.exc import SQLAlchemyError
from datetime import datetime
import logging

# Setup logging
logger = logging.getLogger(__name__)

def insert(username: str, password: str,telephone:str =None,email:str =None) -> bool:
    try:
        current_datetime = datetime.now()
        info = User(id=str(uuid.uuid4()), username=username,password=password,telephone=telephone,email=email, timestamp=current_datetime)
        db.session.add(info)
        db.session.commit()
        logger.info(f"Inserted user with id: {info.id}")
        return True
    except SQLAlchemyError as e:
        db.session.rollback()
        logger.error(f"Error inserting user: {e}")
        return False

def delete(id: str) -> bool:
    try:
        info = User.query.get(id)
        if info:
            db.session.delete(info)
            db.session.commit()
            logger.info(f"Deleted alarm with id: {info.id}")
            return True
        logger.warning(f"User with id: {id} not found")
        return False
    except SQLAlchemyError as e:
        db.session.rollback()
        logger.error(f"Error deleting user: {e}")
        return False
def exist(name: str) -> bool:
    try:
        count = User.query.filter(User.username==name).count()
        return count
    except SQLAlchemyError as e:
        logger.error(f"Error deleting user: {e}")
        return 0        

def findOne(name: str) -> bool:
    try:
        row = User.query.filter(User.username==name).first()
        return row
    except SQLAlchemyError as e:
        logger.error(f"Error deleting user: {e}")
        return 0   

def get(page: int = 1, per_page: int = 10, username: str = None) -> dict:
    try:
        logger.info(f"Fetching users for page: {page}, per_page: {per_page}, username: {username}")
        query = User.query.order_by(User.timestamp.desc())
      
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        users = [user.to_dict() for user in pagination.items]
        logger.info(f"Retrieved {len(users)} users from page {page}, total items: {pagination.total}, total pages: {pagination.pages}")
        return {
            "items": users,
            "total": pagination.total
        }
    except SQLAlchemyError as e:
        logger.error(f"Error retrieving users: {e}")
        return {"users": [], "total_pages": 0, "current_page": 0, "total_items": 0}


def update(id: str, username: str, password: str,telephone:str =None,email:str =None) -> bool:
    try:
        info = User.query.get(id)
        if info:
            info.username = username
            info.password = password
            info.telephone = telephone
            info.email = email
            info.timestamp = datetime.now()  # 更新修改时间
            db.session.commit()
            logger.info(f"Updated user with id: {info.id}")
            return True
        logger.warning(f"User with id: {id} not found")
        return False
    except SQLAlchemyError as e:
        db.session.rollback()
        logger.error(f"Error updating task: {e}")
        return False
